﻿/******************************************************************
 * 功能描述：提供对WebApi访问的一些公共函数
 * 创建时间：2013-07-10
 * 作者：Panxinming
 * 版本：1.0
 * 修订描述：
 * 最后修订日期：
 * Create: 2013-12-02 By Panxinming
 ******************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using ThinkDev.Logging;

namespace EMoney.IStock.Client.Framework
{
    public class WebApiHelper
    {
        /// <summary>
        /// 按照OpenAPI规则生成对应URL，主要为原始URL增加签名
        /// </summary>
        /// <param name="sUrl"></param>
        /// <param name="md5Key"></param>
        /// <returns></returns>
        public static string CreateUrl(string sUrl, string md5Key = "")
        {
            Uri uri;
            if (!Uri.TryCreate(sUrl, UriKind.RelativeOrAbsolute, out uri))
            {
                return sUrl;
            }

            List<string> list = new List<string>();
            string queryStr = uri.Query;
            if (queryStr.IndexOf("?") == 0)
            {
                queryStr = queryStr.Substring(1);
            }
            string[] querys = queryStr.Split('&');
            foreach (string q in querys)
            {
                list.Add(q);
            }
            list.Sort();
            StringBuilder sBuilder = new StringBuilder();
            foreach (string q in list)
            {
                sBuilder.Append(q);
            }

            string toEncrypt = string.Empty;
            if (string.IsNullOrEmpty(md5Key))
            {
                toEncrypt = sBuilder.ToString() + ConfigHelper.WebApiEncryptKey;
            }
            else
            {
                toEncrypt = sBuilder.ToString() + md5Key;
            }

            string md5New = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(toEncrypt, "md5");
            //LogManager.DefaultLogger.Info(toEncrypt + "==>" + md5New);
            return sUrl + "&encrypt=" + md5New;
        }

        /// <summary>
        /// 生成签名EncryptKey
        /// </summary>
        /// <param name="sUrl"></param>
        /// <param name="md5Key">encrypt</param>
        /// <returns></returns>
        public static string CreateEncryptKey(string sUrl, string md5Key = "")
        {
            Uri uri;
            if (!Uri.TryCreate(sUrl, UriKind.RelativeOrAbsolute, out uri))
            {
                return sUrl;
            }

            List<string> list = new List<string>();
            string queryStr = uri.Query;
            if (queryStr.IndexOf("?") == 0)
            {
                queryStr = queryStr.Substring(1);
            }
            string[] querys = queryStr.Split('&');
            foreach (string q in querys)
            {
                list.Add(q);
            }
            list.Sort();
            StringBuilder sBuilder = new StringBuilder();
            foreach (string q in list)
            {
                sBuilder.Append(q);
            }

            string toEncrypt = string.Empty;
            if (string.IsNullOrEmpty(md5Key))
            {
                toEncrypt = sBuilder.ToString() + ConfigHelper.WebApiEncryptKey;
            }
            else
            {
                toEncrypt = sBuilder.ToString() + md5Key;
            }

            string md5New = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(toEncrypt, "md5");
            //LogManager.DefaultLogger.Info(toEncrypt + "==>" + md5New);
            return md5New;
        }

        /// <summary>
        /// WebApi加密密钥
        /// </summary>
        private static string WebApiEncryptKey
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["WebApiEncryptKey"];
            }
        }

        /// <summary>
        /// 以Get协议调用WebApi，默认utf-8协议
        /// </summary>
        /// <param name="baseUrl"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        private static string CallGetApi(string baseUrl, string query)
        {
            try
            {
                string apiUrl = CreateUrl(baseUrl + "?" + query, WebApiEncryptKey);
                HttpWebRequest request = WebRequest.Create(apiUrl) as HttpWebRequest;
                request.Method = "GET";
                request.KeepAlive = false;
                request.ContentType = "application/json";
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                System.IO.Stream responseStream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
                string srcString = reader.ReadToEnd();
                LogManager.WebApiLogger.Info("WebApiHelper=>CallGetApi [" + baseUrl + "] [" + query + "] [" + srcString + "]");
                return srcString;
            }
            catch (WebException wex)
            {
                LogManager.WebApiLogger.Error(wex, "WebApiHelper=>CallGetApi 发生WebException异常[" + wex.Message + "]： [" + baseUrl + "][" + query + "]");
                return wex.Message;
            }
            catch (Exception ex)
            {
                LogManager.WebApiLogger.Error(ex, "WebApiHelper=>CallGetApi 发生Exception异常[" + ex.Message + "]： [" + baseUrl + "][" + query + "]");
                return ex.Message;
            }
        }

        /// <summary>
        /// 以Get协议调用WebApi，传入拼装好的ApiUrl
        /// </summary>
        /// <param name="url"></param>
        /// <param name="encode"></param>
        /// <returns></returns>
        public static string CallGetApi(string url, Encoding encode)
        {
            try
            {
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = "GET";
                request.KeepAlive = false;
                request.ContentType = "application/json";
                request.Timeout = 3000;

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                System.IO.Stream responseStream = response.GetResponseStream();
                System.IO.StreamReader reader;
                reader = new System.IO.StreamReader(responseStream, encode);
                string srcString = reader.ReadToEnd();
                LogManager.WebApiLogger.Info("WebApiHelper=>CallGetApi [" + url + "] [" + srcString + "]");
                return srcString;
            }
            catch (WebException wex)
            {
                LogManager.WebApiLogger.Error(wex, "WebApiHelper=>CallGetApi 发生WebException异常[" + wex.Message + "]： [" + url + "]");
                return wex.Message;
            }
            catch (Exception ex)
            {
                LogManager.WebApiLogger.Error(ex, "WebApiHelper=>CallGetApi 发生Exception异常[" + ex.Message + "]： [" + url + "]");
                return ex.Message;
            }

        }

        /// <summary>
        /// 以Get协议调用WebApi，传入拼装好的ApiUrl，默认utf-8协议
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string CallGetApi(string url)
        {
            try
            {
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = "GET";
                request.KeepAlive = false;
                request.ContentType = "application/json";
                request.Timeout = 3000;

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                System.IO.Stream responseStream = response.GetResponseStream();
                System.IO.StreamReader reader;
                reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
                string srcString = reader.ReadToEnd();
                LogManager.WebApiLogger.Info("WebApiHelper=>CallGetApi [" + url + "] [" + srcString + "]");
                return srcString;
            }
            catch (WebException wex)
            {
                LogManager.WebApiLogger.Error(wex, "WebApiHelper=>CallGetApi 发生WebException异常[" + wex.Message + "]： [" + url + "]");
                return wex.Message;
            }
            catch (Exception ex)
            {
                LogManager.WebApiLogger.Error(ex, "WebApiHelper=>CallGetApi 发生Exception异常[" + ex.Message + "]： [" + url + "]");
                return ex.Message;
            }

        }
        /// <summary>
        /// 获取Api的内容
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string getUrl(string url)
        {
            string ret = string.Empty;
            try
            {
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = "GET";
                request.KeepAlive = false;
                request.ContentType = "application/json";
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                System.IO.Stream responseStream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
                ret = reader.ReadToEnd();
                return ret;
            }
            catch (Exception ex)
            {
                LogManager.WebApiLogger.Error(LogConvert.ParseWebEx(ex), string.Format("getUrl发生异常！[url={0}] [ret={1}]", url, ret));
                return ex.Message;
            }

        }

        public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int timeout, string userAgent, CookieCollection cookies)
        {
            HttpWebRequest request = null;
            //如果是发送HTTPS请求  
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            request.Method = "POST";
            request.ContentType = "application/json";

            //设置代理UserAgent和超时
            //request.UserAgent = userAgent;
            //request.Timeout = timeout; 

            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            //发送POST数据  
            if (!(parameters == null || parameters.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, parameters[key]);
                        i++;
                    }
                }
                byte[] data = Encoding.ASCII.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            string[] values = request.Headers.GetValues("Content-Type");
            return request.GetResponse() as HttpWebResponse;
        }

    }
}
